package com.traffic.api.filter;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.traffic.api.exception.ApiBizException;
import com.traffic.api.filter.filter.IApiFilter;
import com.traffic.api.jedis.JedisClient;
import com.traffic.api.util.OrderInfoContext;
import com.traffic.api.util.StringTool;
import com.traffic.api.util.UtilsUtils;
import com.traffic.managent.model.system.Customer;
import com.traffic.managent.model.system.Product;
import com.traffic.managent.model.system.User;
import com.traffic.managent.service.order.bean.OrderBean;

public class ApiOrderFactoryFilter {
	
	private static Logger logger = Logger.getLogger(ApiOrderFactoryFilter.class);
	
	static List<IApiFilter> rules = new ArrayList<IApiFilter>();
	static JedisClient client = JedisClient.getInstance();

	public static final void check(Map<String, Object> param) {

		String callbackUrl = (String) param.get("callbackUrl");
		String phoneNo = (String) param.get("phoneNo");
		String vasPid = (String) param.get("productId");
		String appkey = (String) param.get("appkey");
		String cstmOrderNo = (String) param.get("cstmOrderNo");

		String userId = null;
		String orderFrom = "1";// 通过接口开通
		String payMode = "0";// 线下付款;

		String phoneProvince = null;
		String operator = null;
		String phoneAreaCode = null;

		String vasProdName = null;
		BigDecimal vasproductPrice = null;
		int vasproductSize = 0;
		String customerId = null;
		String customerName = null;
		String department = null;// 用户的组织机构

		// 1,判断是否重复订单
		if (cstmOrderNo != null && !"".equals(cstmOrderNo)) {
			boolean exists = client.exists("orderno_" + cstmOrderNo+"accept");
			if (exists) {
				throw new ApiBizException(new Throwable("重复的订单号"));
			}
		}

		// 2,参数判断
		if (appkey == null || "".equals(appkey)) {
			throw new ApiBizException(new Throwable("appkey不能为空"));
		}

		// 3,判断用户是否存在
		boolean exists = client.exists("user_" + appkey);
		if (!exists) {
			throw new ApiBizException(new Throwable("未找到用户"));
		} else {
			@SuppressWarnings("rawtypes")
			Map usermap = new HashMap();
			String jsonuser = client.get("user_json" + appkey);
			User user = new Gson().fromJson(jsonuser, User.class);
			usermap = user.getAttrs();

			customerId = (String) usermap.get("customerid");
			department = (String) usermap.get("departmentid");
			userId = (String) usermap.get("ids");
		}
		// 4,号码判断
		if (StringTool.isMobileNO(phoneNo)) {
			throw new ApiBizException(new Throwable("手机号码" + phoneNo + "不正确"));
		}
		// 5,获取号段信息
		String[] info = getPhoneInfo(phoneNo);
		if (info != null && info.length > 1) {
			phoneProvince = info[1];
			operator = info[0];
			phoneAreaCode = info[4];
		} else {
			throw new ApiBizException(new Throwable("手机号码号段" + phoneNo + "未找到"));
		}
		// 6,判断平台产品是否存在
	 
		if ("wanheng".equals(appkey)) {
		
			//本地产品的具体的省份，使用范围，运营商，流量类型，包体大小
			String alleyway = (String) param.get("alleyway");// 0 - 全国通道   1-省份
			String range = (String) param.get("range");//流量类型
			String vasproductId = "";
			if ("0".equals(alleyway)) {
				// province+region+ operator+range+productSize 产品配置规则  region 0 -全国  1-省份
				vasproductId = client.get("1000"+"0"+operator+"0"+vasPid);//全国的产品
			}else {
				if ("0".equals(range)) {//省内漫游月包
					vasproductId = client.get(phoneProvince+"0"+operator+"0"+vasPid);
				}else if ("6".equals(range)) {//日包
					vasproductId = client.get(phoneProvince+"1"+operator+"1"+vasPid);
				}else {//省内漫游日包
					vasproductId = client.get(phoneProvince+"1"+operator+"0"+vasPid);
				}
				
			}
			if (null==vasproductId||"".equals(vasproductId)) {
				throw new ApiBizException(new Throwable("产品已下架"));
			}else {
				vasPid = vasproductId;
			}
					
		}
		
		if ("dianbo".equals(appkey)) {
			String roaming_type = (String) param.get("alleyway");//1 - 全国通道   
			String vasproductId = "";
			if ("1".equals(roaming_type)) {
				vasproductId = client.get("1000"+"0"+operator+"0"+vasPid);//全国的产品
			}else {
				vasproductId = client.get(phoneProvince+"1"+operator+"0"+vasPid);
			}
			if (null==vasproductId||"".equals(vasproductId)) {
				throw new ApiBizException(new Throwable("产品已下架"));
			}else {
				vasPid = vasproductId;
			}
		}
			
		boolean exists2 = client.exists("productvas_" + vasPid);
		
		
		if (!exists2) {
			throw new ApiBizException(new Throwable("产品不存在" + vasPid));
		} else {
			//7.判断供应商产品是否下架
			boolean exists3 = client.exists("vasproduct_" + vasPid);
			if (!exists3) {
				throw new ApiBizException(new Throwable("供应商侧产品已下架" + vasPid));
			}
			//8.判断本地产品是否对该用户关闭通道
			boolean exists4 = client.exists("cusprod_"+customerId+vasPid);
			if (!exists4) {
				throw new ApiBizException(new Throwable("产品折扣未配置" + vasPid));
			}else {
				String sale_flag = client.get("cusprod_"+customerId+vasPid);
				if ("1".equals(sale_flag)) {
					throw new ApiBizException(new Throwable("产品通道已关闭" + vasPid));
				}
			}
			@SuppressWarnings("rawtypes")
			Map productvasmap = new HashMap();

			String jsonProduct = client.get("productvas_json" + vasPid);
			Product productvas = new Gson().fromJson(jsonProduct, Product.class);
			productvasmap = productvas.getAttrs();
			
			vasProdName = (String) productvasmap.get("vasprodname");

			if (productvasmap.get("productprice").toString().contains(".")) {
				vasproductPrice = BigDecimal.valueOf(
						Integer.valueOf(productvasmap.get("productprice").toString().split("\\.")[0].toString()));
			} else {
				vasproductPrice = (BigDecimal) productvasmap.get("productprice");
			}

			if (productvasmap.get("productsize").toString().contains(".")) {
				vasproductSize = Integer.valueOf(productvasmap.get("productsize").toString().split("\\.")[0]);
			} else {
				vasproductSize = Integer.valueOf((String) productvasmap.get("productsize"));
			}
		}
		// 10,判断代理商是否存在
		
	
		Map<String,Object> customermap = new HashMap<String,Object>();
		boolean exists1 = client.exists("customer" + customerId);
		if (!exists1) {
			throw new ApiBizException(new Throwable("代理商账号未找到"));
		} else {
			String jsoncustomer = client.get("customer_json" + customerId);
			Customer customer = new Gson().fromJson(jsoncustomer, Customer.class);
			customermap = customer.getAttrs();
			customerName = (String) customermap.get("customername");
			String isClose = (String) customermap.get("isclose");
			if ("0".equals(isClose)) {//0 - 通道关闭 
				throw new ApiBizException(new Throwable("亲,您的业务通道暂时已关闭哟,需要开启通道请联系管理员"));
			}
			
		}

		// 11,检查客户信控 (需要做缓存处理，人工处理缓存)

//		BigDecimal amount = new BigDecimal(String.valueOf(customermap.get("amount")));
//		BigDecimal giveAmount = new BigDecimal(String.valueOf(customermap.get("giveamount")));
//		BigDecimal creditAmount = new BigDecimal(String.valueOf(customermap.get("creditamount")));
//
//		if (creditAmount.doubleValue() > 0) {// 有信用额度
//			if (amount.add(creditAmount).add(giveAmount).compareTo(vasproductPrice) < 0) {// 充值余额+赠送余额+信用额度<开通产品价格
//				throw new ApiBizException(new Throwable("信用余额不足"));
//			}
//		} else {
//			if (amount.add(giveAmount).compareTo(vasproductPrice) < 0) {// 充值余额+赠送余额<开通产品价格
//				throw new ApiBizException(new Throwable("余额不足"));
//			}
//		}
		
		// 订单生成 并放入队列
		Random random = new Random();
		String rannum = (int) (random.nextDouble() * 9000) + 1000 + "";// 获取4位随机数
		String orderNo = "TRAFFIC" + new Date().getTime() + rannum;
		String orderId = UtilsUtils.getOrderId(29, "Y");
		Date acceptTime = new Date();
		String net = client.get("serverlocalhostip"); // 用来标记服务器地址
		String noRoute = "0";
		String status = "0";// 受理中
		String message = "受理中";

		OrderBean bean = new OrderBean(phoneNo, phoneProvince, phoneAreaCode, operator, vasPid, vasProdName,
				vasproductSize, vasproductPrice, customerId,customerName, userId, department, cstmOrderNo, callbackUrl, orderFrom,
				orderNo, message, status, acceptTime, orderId, payMode, net, noRoute);

		OrderInfoContext.putContext(bean);
		logger.info("ID为"+bean.getIds()+",phoneNo为"+bean.getPhoneNo()+"的订单验证成功!");
	}

	/**
	 * 缓存中获取tel号段信息
	 * 
	 * @param phoneNo
	 */
	private static String[] getPhoneInfo(String phoneNo) {
		String phoneNum = phoneNo.substring(0, 7);
		String ss = client.get("phone_heads_" + phoneNum);
		return ss.split("\\|");
	}

	
}